﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using OnlineBookReader;
using ImageTools.IO;
using ImageTools.IO.Gif;
using ImageTools.IO.Bmp;
using ImageTools.IO.Jpeg;
using ImageTools.IO.Png;
using System.IO;
using System.Net.NetworkInformation;

namespace Reader
{
    public partial class App : Application
    {
        public readonly static Dictionary<string, string> HtmlCache = new Dictionary<string,string>();
        /// <summary>
        /// Initializes a new instance of the App class.
        /// </summary>
        public App()
        {
            if (App.Current.InstallState == InstallState.Installed)
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    App.Current.CheckAndDownloadUpdateCompleted += OnCheckAndDownloadUpdateCompleted;
                    App.Current.CheckAndDownloadUpdateAsync();
                }
                App.Current.UnhandledException += new EventHandler<ApplicationUnhandledExceptionEventArgs>(Current_UnhandledException);
                App.Current.Exit += new EventHandler(Current_Exit);
                
            }

            Startup += delegate
            {
                RootVisual = new SampleBrowser(SampleTreeItems);
            };
            InitializeComponent();
            if (App.Current.IsRunningOutOfBrowser)
            {
                string myDocument = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                ReaderPath.EnsureDirectory(ReaderPath.SitesDirectory);
                ReaderPath.EnsureDirectory(ReaderPath.CacheDirectory);
                if (!File.Exists(ReaderPath.LocalFile))
                {
                    string t = "<?xml version='1.0' encoding='UTF-8'?><LocalBook></LocalBook>";
                    File.WriteAllText(ReaderPath.LocalFile, t);
                }
                if (!File.Exists(ReaderPath.FavoriteFile))
                {
                    string t = "<?xml version='1.0' encoding='UTF-8'?><LocalBook></LocalBook>";
                    File.WriteAllText(ReaderPath.FavoriteFile, t);
                }
            }
            Decoders.AddDecoder<GifDecoder>();
            Decoders.AddDecoder<BmpDecoder>();
            Decoders.AddDecoder<JpegDecoder>();
            Decoders.AddDecoder<PngDecoder>();            
        }

        void Current_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            MessageBox.Show(e.ExceptionObject.StackTrace);
        }

        void Current_Exit(object sender, EventArgs e)
        {
            if (App.Current.IsRunningOutOfBrowser)
            {
                try
                {
                    //有时候Image控件不能即时释放资源
                    Directory.Delete(ReaderPath.CacheDirectory, true);
                }
                catch
                { }
            }
        }
        
        /// <summary>
        /// Checks for the update completed event.
        /// </summary>
        /// <param name="sender">The source object.</param>
        /// <param name="e">The event arguments.</param>
        private void OnCheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e)
        {
            if (e.UpdateAvailable)
            {
                MessageBox.Show("An application update has been downloaded and "
                              + "will be available the next time you start the "
                              + "sample application.");
            }
            else if (e.Error != null)
            {
                MessageBox.Show("While checking for an application update, the "
                              + "following message was encountered:"
                              + Environment.NewLine
                              + Environment.NewLine
                              + e.Error.Message);
            }
        }

        /// <summary>
        /// Gets a collection of SampleTreeItems to populate the SampleBrowser TreeView.
        /// </summary>
        public static IEnumerable<SampleTreeItem> SampleTreeItems
        {
            get
            {
                IEnumerable<object> data = Application.Current.Resources["SampleTreeView"] as IEnumerable<object>;
                return (data != null) ?
                    data.OfType<SampleTreeItem>() :
                    Enumerable.Empty<SampleTreeItem>();
            }
        }

       
    }
}
